<template>
  <div id="lightOnOff" class="wrapper p-4">
    <!--灯火列表-->
    <ul class="light-group d-flex " v-if="lightType=='nb'">
      <li v-for="index in lamps" :key="index" class="mr-3 d-flex flex-column justify-content-center align-items-center"
         :class="{active:lightSels.indexOf(index)!=-1}" @click="lightSelFun(index)">
          <img ref="bulbImg" :src="imgSrc" width="40" height="64">
        <label class="mt-2">火{{index}}</label>
      </li>
    </ul>
    <!--调光-->
    <div class="block ur_border mt-4 p-3">
      <el-radio-group v-model="actionType">
        <el-radio :label="1" class="w120">关灯</el-radio>
        <el-radio :label="2" class="w120">开灯</el-radio>
        <el-radio :label="3" class="w120">调光</el-radio>
      </el-radio-group>
      <el-slider v-model="lightLevel" show-input class="ml-2 mt-2" :disabled="isSlider"></el-slider>
    </div>
    <div class="mt-3">
      <el-tooltip class="item" :content="errors.first('pwd')" :value="errors.has('pwd')" :manual="true">
        <el-input type="password" placeholder="请输入操作密码" class="input-with-select w250" :class="{'is-error':errors.has('pwd')}" size="small" v-model="operatePwd" v-validate="'required'" name="pwd">
          <el-button type="password" slot="append" class="ur-btn ur-btn-primary" :disabled="btnState" @click="send"><i class="iconfont icon-queding"></i>下发</el-button>
        </el-input>
      </el-tooltip>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import api from 'api/api'
  import {mapState} from 'vuex'

  export default {
    components: {},
    props: {
      poles:{
        type:Array,
        default:function () {
          return []
        }
      },
      page:'',
      lightType:'',
      monitorMode:0
    },
    data() {
      return {
        lightLevel:0,
        actionType:1,
        lightSels:[],
        isSlider:true,
        operatePwd:'',
        cPoles:this.poles,
        callNum:{total:0,success:0,error:0},
        // btnState:false,
        lamps:3,
        imgSrc:'static/image/comm/off_light.png'
      }
    },
    watch: {
      actionType(val){
        if(val==3){
          this.isSlider=false
        }else{
          this.isSlider=true
          this.lightLevel=val==2?100:0
        }
      }
    },
    computed: {
      ...mapState({
        btnState: state => state.user.btnState,
      })
    },
    methods: {
      lightSelFun(index){
        if(this.lightSels.indexOf(index)!=-1){
          let sIndex=this.lightSels.indexOf(index)
          this.lightSels.splice(sIndex,1)
        }else{
          this.lightSels.push(index)
        }
      },
      send() {
        let _this=this
        let poleIds=[]
        if(this.lightType=='nb'&&!this.lightSels.length){
          return this.$message.warning({showClose:true,message:'请选择灯泡'})
        }
        this.$validator.validateAll().then((res) => {
          if (res) {
            let pIndex = 1
            this.$store.commit('user/SET_USER_PWD', this.operatePwd)
            this.$store.commit('user/SET_BTN_STATE',true)
            this.cPoles.map((pole, index, arr) => {
              poleIds.push((pole.PoleId||pole.Id||pole.BoxId))
              pole.result = '下发控制中...'
              this.$emit('updateResult',{callNum:this.callNum,PoleIds:poleIds})
              let url,data
              if(this.lightType=='rtu'){
                url='/Communication/Rtu/AFN05F2'
                if(this.monitorMode==1){//rtu(装单灯)
                  data={devAddr:pole.DevAddr,lightLevel:this.lightLevel,rtuXh:0}
                }else{//RTU单灯
                  data={devAddr:pole.BoxDevAddr,lightLevel:this.lightLevel,rtuXh:pole.RtuXh}
                }
              }else if(this.lightType=='rtu_group'){
                url='/Communication/Rtu/AFN05F3'
                data={devAddr:pole.DevAddr,lightLevel:this.lightLevel,groupNo:pole.GroupNo}
              }else{
                url='/Communication/NB/NBSwitchController'
                data={tnDevAddr:pole.PoleDevAddr||pole.DevAddr,lightLevel:this.lightLevel,lampNos:this.lightSels}
              }
              api.fetchSimple(url,data)
                .then(async r => {
                  pole.opereaTime=api.formatDate(new Date(),'yyyy-MM-dd HH:mm:ss')
                  if (r.err) {
                    if(this.page=='gis'){
                      this.$message.error({showClose:true,message:r.err})
                      // if(this.lightType=='nb'){
                      //   this.$refs.bulbImg.map(img=>{
                      //     img.attributes[0]['value']='static/image/comm/off_light.png'
                      //   })
                      // }
                    }
                    this.callNum.error++
                    pole.result = 0
                    pole.resultInfo = r.err
                  }
                  else {
                    if (this.page == 'gis') {//地图给提示
                      this.$message.success({showClose:true,message:['关灯', '开灯', '调光'][this.actionType - 1] + '成功'})
                    }
                    //控制单个nb单灯时 灯状态改变
                    if (this.poles.length == 1 && this.lightType == 'nb') {
                      this.$refs.bulbImg.map((img, index, imgs) => {
                        if (_this.lightSels.indexOf(index + 1) !== -1) {
                          img.attributes[0]['value'] = this.lightLevel != 0 ? 'static/image/comm/light.png' : 'static/image/comm/off_light.png'
                        }
                      })
                    }
                    this.callNum.success++
                    pole.result = 1
                    pole.resultInfo = '/'
                  }
                  let total = this.cPoles.length
                  let pcen = Math.round(pIndex / total * 100) > 100 ? 100 : Math.round(pIndex / total * 100)
                  this.$emit('updateBar',pcen)
                  pIndex++
                  if (pcen==100) {
                    this.callNum.total = this.callNum.error + this.callNum.success
                    this.$emit('updateResult',{callNum:this.callNum,PoleIds:poleIds})
                    this.$store.commit('user/SET_BTN_STATE',false)
                  }
                })
            })
          }
        })
      }
    },
    created() {
      //this.page == 'gis'
      if (this.poles.length==1) {
        this.lamps = this.poles[0]['Lamps']||3
        for (let i = 0; i<this.lamps; i++) {
          this.lightSels.push(i + 1)
        }
      }
    },
    mounted() {
      if (this.poles.length==1&&this.lightType=='nb') {
        this.$refs.bulbImg.map((img,index,imgs) => {
          img.attributes[0]['value'] = this.poles[0]['State' + (index + 1)] == 1 ? 'static/image/comm/light.png' : 'static/image/comm/off_light.png'
        })
      }
    }
  }
</script>
<style  lang="stylus" rel="stylesheet/stylus">
  .light-group{
    li{width: 104px;height: 104px;border:1px solid #ccc;border-radius: 4px;
      &.active{background: #e4f4ff;border-color: #0c8eec}
    }
  }
</style>
